import { CtgyState, FirstCtgy, SecondCtgy, initCtgyState } from "./state"
import { Module } from 'vuex'
import ctgyAPI from '@/api/ctgyApi'

// 分类模块
export const ctgyModule: Module<CtgyState, {}> = {
  namespaced: true, // 将该模块的 actions、mutations、getters 限定在该模块的命名空间内 (在使用时需要加上命名空间前缀)
  state: initCtgyState, // 初始化 state 值
  getters: {
    // 获取 state 中 firstCtgyList 一级分类
    getFirstCtgyList(state) {
      return state.firstCtgyList
    },
    // 获取 state 中 secondCtgyList 二级分类+三级分类
    getSecThirdCtgyList(state) {
      return state.secondCtgyList
    }
  },
  mutations: {
    // 保存1级分类数据
    storeFirstCtgyList(state, firstCtgyList_: FirstCtgy[]) {
      state.firstCtgyList = firstCtgyList_
    },
    // 保存2级+3级分类数据
    storeSecondCtgyList(state, secondCtgyList: SecondCtgy[]) {
      state.secondCtgyList = secondCtgyList
    }
  },
  actions: {
    // 获取1级分类
    async findFirstCtgyList({ commit }) {
      const result = await ctgyAPI.getFirstCtgyList()
      commit('storeFirstCtgyList', result.data)
    },
    // 根据1级分类获取对应的2级分类和3级分类
    async findSecThirdCtgyList({ commit }, firstCtgyId: number) {
      let result = await ctgyAPI.getSecThrdCtgyList(firstCtgyId)
      result.data = result.data.map((secondctgy: SecondCtgy) => {
        secondctgy.isReadyOpen = true // 可以点击展开按钮
        // 扩展 subThirdCtgys 字段里面最多保存5项3级分类
        return (secondctgy.subThirdCtgys = secondctgy.thirdctgys.slice(0, 5), secondctgy)
      })
      commit('storeSecondCtgyList', result.data)
    }
  }
}
